<script setup>
import router from '@/router'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowRightBold,
  ArrowRight,
  User,
  Lock,
  DocumentCopy,
  Avatar,
  PhoneFilled,
  Message,
  SuccessFilled,
  StarFilled,
  UserFilled,
  Warning,
} from '@element-plus/icons-vue'
import { getInfo, logout } from '@/api/login'
import { updateUserProfile, updateUserPwd } from '@/api/user'
import { useUserStore } from '@/stores'
const userStore = useUserStore()

import { baseURL } from '@/utils/request.js'
import DefaultAvatar from '@/assets/images/profile.jpg'
const avatarUrl = ref(userStore.user.avatar ? baseURL + userStore.user.avatar : DefaultAvatar)

function getUserInfo() {
  getInfo().then(res => {
    console.log(res)
    if (res.data.code === 200) {
      userStore.setUser(res.data.user)
    } else {
      ElMessage.error('登录状态已过期，请重新登陆')
      router.push('/login')
    }
  })
}
getUserInfo()

// 个人信息
const myInfoShow = ref(false)

// 编辑资料
const editProfileShow = ref(false)
const profileFormRef = ref()
const profileForm = ref({
  nickName: '',
  phonenumber: '',
  email: '',
  sex: '',
})
const profileRules = ref({
  nickName: [
    { required: true, message: "请输入昵称", trigger: "blur" }
  ],
  phonenumber: [
    { required: true, message: '请输入号码', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'blur' },
  ],
})
function editProfile() {
  if (profileFormRef.value) {
    profileFormRef.value.resetFields()
  }
  editProfileShow.value = true
  getInfo().then(res => {
    console.log(res.data.user)
    profileForm.value = res.data.user
  })
}
function saveProfile() {
  profileFormRef.value.validate(valid => {
    if (valid) {
      updateUserProfile(profileForm.value).then(res => {
        if (res.data.code === 200) {
          ElMessage.success('保存成功')
          editProfileShow.value = false
          getUserInfo()
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    }
  })
}

// 修改密码
const pwdShow = ref(false)
const pwdFormRef = ref()
const pwdForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})
const pwdRules = ref({
  oldPassword: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 5, message: '密码长度不能小于5位', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, message: '密码长度不能小于5位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 5, message: '密码长度不能小于5位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPassword) {
          callback(new Error('新密码与确认密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
})
function updatePwd() {
  if (pwdFormRef.value) {
    pwdFormRef.value.resetFields()
  }
  pwdShow.value = true
}
function savePwd() {
  pwdFormRef.value.validate(valid => {
    if (valid) {
      updateUserPwd(pwdForm.value.oldPassword, pwdForm.value.newPassword).then(res => {
        console.log(res)
        if (res.data.code === 200) {
          ElMessage.success('修改成功')
          pwdShow.value = false
          logout().then(res => {
            userStore.removeToken()
            userStore.removeUser()
            router.push('/login')
            ElMessage.error('密码已修改，请重新登录')
          })
        } else {
          ElMessage.error(res.data.msg)

        }
      })
    }
  })
}

// 退出登录
function exit() {
  ElMessageBox.confirm('是否确定退出登录？', '提示', {
    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',
  }).then(() => {
    logout().then(res => {
      ElMessage.success(res.data.msg)
      userStore.removeToken()
      userStore.removeUser()
      router.push('/login')
    })
  }).catch(() => { })
}
</script>

<template>
  <div class="user">
    <el-container>
      <el-header>个人中心</el-header>
      <el-main>
        <!-- 个人信息 -->
        <div class="my-info">
          <div class="info">
            <el-avatar :size="50" :src="avatarUrl" />
            <div class="name">
              <p style="font-size: 18px;font-weight: bold;">{{ userStore.user.nickName }}</p>
              <p style="font-size: 14px;">学号：{{ userStore.user.userName }}</p>
            </div>
          </div>
          <el-button color="#000000" link @click="myInfoShow = true">
            <span>个人信息</span>
            <el-icon>
              <ArrowRightBold />
            </el-icon>
          </el-button>
        </div>
        <!-- 选项卡 -->
        <div class="select-card">
          <div class="option" @click="editProfile">
            <span>
              <el-icon color="#409EFF" size="16">
                <User />
              </el-icon>
              编辑资料
            </span>
            <el-icon size="16">
              <ArrowRight />
            </el-icon>
          </div>
          <div class="option" @click="updatePwd">
            <span>
              <el-icon color="#409EFF" size="16">
                <Lock />
              </el-icon>
              修改密码
            </span>
            <el-icon size="16">
              <ArrowRight />
            </el-icon>
          </div>
          <div class="option">
            <span>
              <el-icon color="#409EFF" size="16">
                <DocumentCopy />
              </el-icon>
              预约记录
            </span>
            <el-icon size="16">
              <ArrowRight />
            </el-icon>
          </div>
          <div class="option">
            <span>
              <el-icon color="#409EFF" size="16">
                <Warning />
              </el-icon>
              违约记录
            </span>
            <el-icon size="16">
              <ArrowRight />
            </el-icon>
          </div>
        </div>
        <!-- 退出登录 -->
        <el-button class="logout" type="danger" plain @click="exit">退出登录</el-button>
      </el-main>

      <!-- 个人信息 -->
      <el-dialog title="个人信息" v-model="myInfoShow" width="90%">
        <div class="personal-data">
          <p>
            <span>
              <el-icon>
                <StarFilled />
              </el-icon>
              学号:
            </span>
            {{ userStore.user.userName }}
          </p>
          <p>
            <span>
              <el-icon>
                <Avatar />
              </el-icon>
              昵称:
            </span>
            {{ userStore.user.nickName }}
          </p>
          <p>
            <span>
              <el-icon>
                <UserFilled />
              </el-icon>
              性别:
            </span>
            {{ userStore.user.sex == 0 ? '男' : '女' }}
          </p>
          <p>
            <span>
              <el-icon>
                <PhoneFilled />
              </el-icon>
              手机号码:
            </span>
            {{ userStore.user.phonenumber }}
          </p>
          <p>
            <span>
              <el-icon>
                <Message />
              </el-icon>
              邮箱:
            </span>
            {{ userStore.user.email }}
          </p>
          <p>
            <span>
              <el-icon>
                <SuccessFilled />
              </el-icon>
              账号创建日期:
            </span>
            {{ userStore.user.createTime }}
          </p>
        </div>
      </el-dialog>

      <!-- 编辑资料 -->
      <el-dialog title="编辑资料" v-model="editProfileShow" width="90%">
        <el-form ref="profileFormRef" :model="profileForm" :rules="profileRules">
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="profileForm.nickName" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="号码" prop="phonenumber">
            <el-input v-model="profileForm.phonenumber" placeholder="请输入号码" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="profileForm.sex">
              <el-radio value="0">男</el-radio>
              <el-radio value="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editProfileShow = false">取消</el-button>
          <el-button type="primary" @click="saveProfile">保存</el-button>
        </template>
      </el-dialog>

      <!-- 修改密码 -->
      <el-dialog title="修改密码" v-model="pwdShow" width="90%">
        <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="auto">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input type="password" v-model="pwdForm.oldPassword" placeholder="请输入旧密码" />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="pwdForm.newPassword" placeholder="请输入新密码" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="pwdForm.confirmPassword" placeholder="请输入确认密码" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="pwdShow = false">取消</el-button>
          <el-button type="primary" @click="savePwd">修改</el-button>
        </template>
      </el-dialog>

    </el-container>
  </div>
</template>

<style lang="scss" scoped>
.user {
  height: 100%;

  .el-container {
    height: 100%;

    .el-header {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 40px;
      color: #555555;
      font-size: 16px;
      background-color: #ffffff;
    }

    .el-main {
      padding: 5px;

      .my-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 25px 20px;
        color: #ffffff;
        background: linear-gradient(135deg, #409EFF, #36cfc9);
        border-radius: 8px;

        .info {
          display: flex;
          align-items: center;
          gap: 10px;
        }
      }

      .select-card {
        display: flex;
        flex-direction: column;
        gap: 2px;
        margin: 10px 0;
        border-radius: 4px;
        overflow: hidden;

        .option {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 15px 15px;
          width: 100%;
          color: #555555;
          background-color: #ffffff;
          cursor: pointer;

          span {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 15px;
          }
        }
      }

      .logout {
        width: 100%;
        height: 40px;
        border-radius: 50px;
      }
    }

    .personal-data {
      p {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 15px 0;
        color: #555555;
        font-size: 12px;
        border-bottom: 1px solid #eeeeee;

        span {
          display: flex;
          align-items: center;
          gap: 5px;
        }
      }
    }
  }
}
</style>